package com.rem.concurrency.juc.my13Single;

import java.lang.reflect.Constructor;

/**
 * DCL 懒汉式
 * 反射 创建多个对象 加锁拦截
 *
 * @author Rem
 * @date 2021-03-10
 */

public class LazyMan4 {


    /**
     * volatile 避免指定重排
     */
    private volatile static LazyMan4 lazyMan;


    /**
     * 构造加锁
     */
    private LazyMan4() {
        synchronized (LazyMan4.class) {
            if (lazyMan != null) {
                throw new RuntimeException("不要试图通过反射创建单例");
            }
        }
        System.out.println(Thread.currentThread().getName() + "ok");
    }


    /**
     * 双层检测的锁模式 DCL懒汉式
     *
     * @return
     */
    public static LazyMan4 getLazyMan() {
        //加锁操作
        if (lazyMan == null) {
            //加锁
            synchronized (LazyMan4.class) {
                if (lazyMan == null) {
                    //不是一个原子性的操作
                    lazyMan = new LazyMan4();
                }
            }
        }
        return lazyMan;
    }

    public static void main(String[] args) throws Exception {


        LazyMan4 lazyMan0 = LazyMan4.getLazyMan();
        Class<LazyMan4> aClass = LazyMan4.class;
        Constructor<LazyMan4> declaredConstructor = aClass.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);

        LazyMan4 lazyManA = declaredConstructor.newInstance();

        System.out.println(lazyMan0);
        System.out.println(lazyManA);
    }
}